import type { Reducer, Effect } from 'umi';
import { history } from 'umi';
import { fakeAccountLogin, layout } from '@/services/login';
import { clearLocalStorage } from '@/utils/localStorage';
import { message } from 'antd';

export interface StateType {
  status?: 'ok' | 'error';
  type?: string;
  currentAuthority?: 'user' | 'guest' | 'admin';
}

export interface LoginModelType {
  namespace: string;
  state: StateType;
  effects: {
    login: Effect;
    logout: Effect;
  };
  reducers: {
    changeLoginStatus: Reducer<StateType>;
  };
}

const Model: LoginModelType = {
  namespace: 'login',

  state: {},

  effects: {
    *login({ payload }, { call, put }) {
      console.log(payload);
      const response = yield call(fakeAccountLogin, payload);

      if (response.status === undefined) {
        yield put({
          type: 'changeLoginStatus',
          payload: response,
        });

        // 登录成功跳转到首页
        history.replace('/');
        message.success('🎉🎉🎉登录成功');
      }
    },

    *logout(_, { call }) {
      // 1、请求 api
      const hide = message.loading('退出中。。。');
      const res = yield call(layout);
      if (res.status) {
        return;
      }
      hide();
      // 2、删除本地存储
      clearLocalStorage();
      // 3、重定向到登录页
      history.replace('/login');
    },
  },

  reducers: {
    changeLoginStatus(state, { payload }) {
      // 将token存入 LocalStorage
      localStorage.setItem('access_token', payload.access_token);
      return {
        ...state,
      };
    },
  },
};

export default Model;
